import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { printerApi } from '../../services/printerApi';
import './printer-list.css';

const PrinterList: React.FC = () => {
  const navigate = useNavigate();
  const [printers, setPrinters] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statistics, setStatistics] = useState({
    totalPrinters: 0,
    totalPrints: 0,
    onlinePrinters: 0
  });

  const fetchPrinters = async () => {
    try {
      setLoading(true);
      setError(null);
      console.log('开始获取打印机列表');
      const response = await printerApi.getPrinters();
      console.log('获取打印机列表响应:', {
        response,
        timestamp: new Date().toISOString()
      });
      
      const printersList = response?.printers || [];
      console.log('设置打印机列表:', {
        printers: printersList,
        timestamp: new Date().toISOString()
      });
      
      setPrinters(printersList);
      
      // 计算统计信息
      const totalPrints = printersList.reduce((sum: number, printer: any) => 
        sum + (printer.printCount || 0), 0);
      
      const onlinePrinters = printersList.filter((printer: any) => 
        printer.isOnline).length;
      
      setStatistics({
        totalPrinters: printersList.length,
        totalPrints,
        onlinePrinters
      });
    } catch (err: any) {
      console.error('获取打印机列表失败:', {
        error: err,
        message: err.message,
        response: err.response?.data,
        timestamp: new Date().toISOString()
      });
      setError('获取打印机列表失败，请重试');
      setPrinters([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPrinters();
  }, []);

  const handleAddPrinter = () => {
    navigate('/printer/add');
  };

  const handleDeletePrinter = async (printerId: string) => {
    if (!window.confirm('确定要删除这台打印机吗？')) {
      return;
    }

    try {
      setLoading(true);
      const result = await printerApi.deletePrinter(printerId);
      
      if (result.success) {
        console.log('打印机删除成功:', result.message);
        // 重新获取打印机列表
        await fetchPrinters();
      } else {
        console.error('删除打印机失败:', result.message);
        setError(`删除打印机失败: ${result.message}`);
      }
    } catch (err: any) {
      console.error('删除打印机操作失败:', err);
      setError(`删除打印机失败: ${err.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  const handlePrinterClick = (printerId: string) => {
    navigate(`/printer/${printerId}`);
  };

  const handleSyncSystemPrinters = async () => {
    try {
      setLoading(true);
      console.log('开始同步系统打印机');
      
      // 调用同步API
      await printerApi.syncSystemPrinters();
      console.log('系统打印机同步完成');
      
      // 重新获取打印机列表
      await fetchPrinters();
    } catch (err) {
      console.error('同步系统打印机失败:', err);
      setError('同步系统打印机失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="printer-list-container">
        <div className="printer-list-header">
          <h1>打印机管理</h1>
        </div>
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p className="loading-text">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="printer-list-container">
      <div className="printer-list-header">
        <h1>打印机管理</h1>
        <div className="printer-list-actions">
          <button className="btn btn-primary" onClick={handleAddPrinter}>
            <i className="fas fa-plus"></i>
            添加打印机
          </button>
          <button className="btn btn-info" onClick={handleSyncSystemPrinters}>
            <i className="fas fa-sync"></i>
            同步系统打印机
          </button>
        </div>
      </div>

      {error && <div className="error-message">{error}</div>}

      <div className="statistics-panel">
        <div className="stat-item">
          <div className="stat-value">{statistics.totalPrinters}</div>
          <div className="stat-label">总打印机数量</div>
        </div>
        <div className="stat-item">
          <div className="stat-value">{statistics.onlinePrinters}</div>
          <div className="stat-label">在线打印机</div>
        </div>
        <div className="stat-item">
          <div className="stat-value">{statistics.totalPrints}</div>
          <div className="stat-label">总打印次数</div>
        </div>
      </div>

      {printers.length > 0 ? (
        <div className="printer-grid">
          {printers.map((printer) => (
            <div 
              key={printer.id} 
              className="printer-card"
              onClick={() => handlePrinterClick(printer.id)}
            >
              <div className="printer-card-header">
                <h3>{printer.name}</h3>
                <div className="printer-actions">
                  <button
                    className="btn btn-danger"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeletePrinter(printer.id);
                    }}
                  >
                    <i className="fas fa-trash"></i>
                    删除
                  </button>
                </div>
              </div>
              <div className="printer-info">
                <div className="info-item">
                  <span className="label">状态</span>
                  <span className={`status ${printer.isOnline ? 'online' : 'offline'}`}>
                    {printer.isOnline ? '在线' : '离线'}
                  </span>
                </div>
                <div className="info-item">
                  <span className="label">类型</span>
                  <span className="value">
                    {printer.isSystemPrinter ? '系统打印机' : '网络打印机'}
                  </span>
                </div>
                {!printer.isSystemPrinter && printer.ip && (
                  <div className="info-item">
                    <span className="label">IP地址</span>
                    <span className="value">{printer.ip}</span>
                  </div>
                )}
                {!printer.isSystemPrinter && printer.port && (
                  <div className="info-item">
                    <span className="label">端口</span>
                    <span className="value">{printer.port}</span>
                  </div>
                )}
                {printer.protocol && (
                  <div className="info-item">
                    <span className="label">协议</span>
                    <span className="value">{printer.protocol}</span>
                  </div>
                )}
              </div>
              <div className="printer-stats">
                <div className="stat">
                  <div className="label">打印次数</div>
                  <div className="value">{printer.printCount || 0}</div>
                </div>
                <div className="stat">
                  <div className="label">失败次数</div>
                  <div className="value">{printer.failedPrintCount || 0}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="empty-state">
          <p>还没有添加任何打印机</p>
          <button className="btn btn-primary" onClick={handleAddPrinter}>
            <i className="fas fa-plus"></i>
            添加打印机
          </button>
        </div>
      )}
    </div>
  );
};

export default PrinterList;
